package controller

import (
	"blog_server/global"
	"blog_server/internal/model/request"
	"blog_server/internal/service"
	"blog_server/pkg/app"
	"blog_server/pkg/errcode"
	"blog_server/pkg/util"
	"github.com/gin-gonic/gin"
)

type UserController struct{}

func NewUserController() UserController {
	return UserController{}
}

func (u *UserController) Login(c *gin.Context) {
	response := app.NewResponse(c)
	param := request.LoginRequest{}
	svc := service.New(c.Request.Context())
	err := c.ShouldBind(&param)
	if err != nil {
		global.Logger.Errorf("c.ShouldBind errs: %v", err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}
	user, err := svc.GetUserByName(param.Username)
	if err != nil {
		global.Logger.Errorf("%s 用户不存在: %v", user.Username, err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}
	if !util.ValidatePasswords(user.Password, []byte(param.Password)) {
		global.Logger.Errorf("%s 密码错误: %v", user.Username, err)
		response.ToErrorResponse(errcode.PwdError)
		return
	}
	token, err := app.GenerateToken(user.Username, user.Role, user.Avatar)
	if err != nil {
		global.Logger.Errorf("app.GenerateToken: %v", err)
		response.ToErrorResponse(errcode.ServerError)
		return
	}
	response.ToSuccessResponse(gin.H{"token": token})
}

func (u *UserController) Info(c *gin.Context) {
	response := app.NewResponse(c)
	token := c.Query("token")
	info, err := app.ParseToken(token)
	if err != nil {
		global.Logger.Errorf("app.ParseToken: %v", err)
		response.ToErrorResponse(errcode.UnauthorizedTokenError)
		return
	}
	response.ToSuccessResponse(gin.H{
		"avatar": info.Avatar,
		"role":   info.Role,
		"name":   info.Username})
}

func (u *UserController) Logout(c *gin.Context) {
	response := app.NewResponse(c)
	response.ToSuccessResponse(nil)
}
